import 'package:flutter/material.dart';
import '../../Model/post.dart';

class DataTableDemo extends StatefulWidget {
  DataTableDemo({Key key}) : super(key: key);

  @override
  _DataTableDemoState createState() => _DataTableDemoState();
}

class _DataTableDemoState extends State<DataTableDemo> {
  int _sortColumnIndex;
  bool _sortAscending = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DataTableDemo'),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(8.0),
        child: ListView(
          children: <Widget>[
            DataTable(
              horizontalMargin: 20,
              columnSpacing: 20,
              sortColumnIndex: _sortColumnIndex,
              sortAscending: _sortAscending,
              dataRowHeight: 80,
              columns: [
                DataColumn(
                  label: Text('title'),
                  onSort: (int index, bool isAccending) {
                    setState(() {
                      _sortColumnIndex = index;
                      _sortAscending = isAccending;

                      posts.sort((a,b) {
                        if (!isAccending) {
                          final c = a;
                          a = b;
                          b = c;
                        }

                        return a.title.length.compareTo(b.title.length);
                      });
                    });
                  }
                ),
                DataColumn(
                  label: Text('author')
                ),
                DataColumn(
                  label: Text('image')
                ),
              ], 
              rows: posts.map((Post item){
                return DataRow(
                  selected:item.selected,
                  onSelectChanged: (bool select){
                    setState(() {
                      item.selected = select;
                    });
                  },
                  cells: [
                    DataCell(
                      Container(
                        width: 120,
                        child: Text(item.title)
                      )
                    ),
                    DataCell(
                      Container(
                        child: Text(item.author)
                      )
                    ),
                    DataCell(
                      Image.network(item.imageUrl, fit: BoxFit.cover,)
                    )
                  ]
                );
              }).toList()
            )
          ],
        ),
      )
    );
  }
}